//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package admin_sw_strore_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas/api-server/admin_api_serv/admin_common"
	"atomgit.com/openlinksaas/api-server/config"
	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/sw_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/sw_store_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

type SwStoreAdminApiImpl struct {
	sw_store_api.UnimplementedSwStoreAdminApiServer
	adminCfg *config.AdminCfg
}

func NewSwStoreAdminApiImpl(adminCfg *config.AdminCfg) *SwStoreAdminApiImpl {
	return &SwStoreAdminApiImpl{adminCfg: adminCfg}
}

func (apiImpl *SwStoreAdminApiImpl) AddCate(ctx context.Context, req *sw_store_api.AdminAddCateRequest) (*sw_store_api.AdminAddCateResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &sw_store_api.AdminAddCateResponse{
			Code:   sw_store_api.AdminAddCateResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &sw_store_api.AdminAddCateResponse{
			Code:   sw_store_api.AdminAddCateResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SwStorePerm.AddCate {
		return &sw_store_api.AdminAddCateResponse{
			Code:   sw_store_api.AdminAddCateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	nowTime := time.Now().UnixNano() / 1e6
	cateId := uuid.NewString()
	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = sw_dao.CateDao.Insert(sessCtx, &sw_dao.SoftWareCateInfoDbItem{
			CateId:        cateId,
			CateName:      req.CateName,
			Weight:        req.Weight,
			SoftWareCount: 0,
			CreateTime:    nowTime,
			UpdateTime:    nowTime,
		})
		if err != nil {
			return nil, err
		}
		return &sw_store_api.AdminAddCateResponse{
			Code:   sw_store_api.AdminAddCateResponse_CODE_OK,
			CateId: cateId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*sw_store_api.AdminAddCateResponse), nil
}

func (apiImpl *SwStoreAdminApiImpl) UpdateCate(ctx context.Context, req *sw_store_api.AdminUpdateCateRequest) (*sw_store_api.AdminUpdateCateResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &sw_store_api.AdminUpdateCateResponse{
			Code:   sw_store_api.AdminUpdateCateResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &sw_store_api.AdminUpdateCateResponse{
			Code:   sw_store_api.AdminUpdateCateResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SwStorePerm.UpdateCate {
		return &sw_store_api.AdminUpdateCateResponse{
			Code:   sw_store_api.AdminUpdateCateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := sw_dao.CateDao.Exist(ctx, req.CateId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &sw_store_api.AdminUpdateCateResponse{
			Code:   sw_store_api.AdminUpdateCateResponse_CODE_NO_CATE,
			ErrMsg: "软件分类不存在",
		}, nil
	}

	nowTime := time.Now().UnixNano() / 1e6
	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = sw_dao.CateDao.Update(sessCtx, req.CateId, req.CateName, req.Weight, nowTime)
		if err != nil {
			return nil, err
		}
		return &sw_store_api.AdminUpdateCateResponse{
			Code: sw_store_api.AdminUpdateCateResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*sw_store_api.AdminUpdateCateResponse), nil
}

func (apiImpl *SwStoreAdminApiImpl) RemoveCate(ctx context.Context, req *sw_store_api.AdminRemoveCateRequest) (*sw_store_api.AdminRemoveCateResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &sw_store_api.AdminRemoveCateResponse{
			Code:   sw_store_api.AdminRemoveCateResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &sw_store_api.AdminRemoveCateResponse{
			Code:   sw_store_api.AdminRemoveCateResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SwStorePerm.RemoveCate {
		return &sw_store_api.AdminRemoveCateResponse{
			Code:   sw_store_api.AdminRemoveCateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	cateItem, err := sw_dao.CateDao.Get(ctx, req.CateId)
	if err != nil { //记录不存在
		return &sw_store_api.AdminRemoveCateResponse{
			Code: sw_store_api.AdminRemoveCateResponse_CODE_OK,
		}, nil
	}
	if cateItem.SoftWareCount > 0 {
		return &sw_store_api.AdminRemoveCateResponse{
			Code:   sw_store_api.AdminRemoveCateResponse_CODE_HAS_SOFT_WARE,
			ErrMsg: "分类下包含软件",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = sw_dao.CateDao.Remove(sessCtx, req.CateId)
		if err != nil {
			return nil, err
		}
		return &sw_store_api.AdminRemoveCateResponse{
			Code: sw_store_api.AdminRemoveCateResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*sw_store_api.AdminRemoveCateResponse), nil
}

func (apiImpl *SwStoreAdminApiImpl) AddSoftWare(ctx context.Context, req *sw_store_api.AdminAddSoftWareRequest) (*sw_store_api.AdminAddSoftWareResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &sw_store_api.AdminAddSoftWareResponse{
			Code:   sw_store_api.AdminAddSoftWareResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &sw_store_api.AdminAddSoftWareResponse{
			Code:   sw_store_api.AdminAddSoftWareResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SwStorePerm.AddSoftWare {
		return &sw_store_api.AdminAddSoftWareResponse{
			Code:   sw_store_api.AdminAddSoftWareResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := sw_dao.CateDao.Exist(ctx, req.CateId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &sw_store_api.AdminAddSoftWareResponse{
			Code:   sw_store_api.AdminAddSoftWareResponse_CODE_NO_CATE,
			ErrMsg: "软件分类不存在",
		}, nil
	}

	nowTime := time.Now().UnixNano() / 1e6
	swId := uuid.NewString()
	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		osList := []uint32{}
		for _, osType := range req.OsList {
			osList = append(osList, uint32(osType))
		}
		err = sw_dao.SoftwareDao.Insert(sessCtx, &sw_dao.SoftWareInfoDbItem{
			SwId:        swId,
			SwName:      req.SwName,
			SwDesc:      req.SwDesc,
			CateId:      req.CateId,
			Weight:      req.Weight,
			Recommend:   req.Recommend,
			OsList:      osList,
			DownloadUrl: req.DownloadUrl,
			IconFileId:  req.IconFileId,
			CreateTime:  nowTime,
			UpdateTime:  nowTime,
		})
		if err != nil {
			return nil, err
		}
		count, err := sw_dao.SoftwareDao.CountByCate(sessCtx, req.CateId)
		if err != nil {
			return nil, err
		}
		err = sw_dao.CateDao.UpdateSoftWareCount(sessCtx, req.CateId, count)
		if err != nil {
			return nil, err
		}
		return &sw_store_api.AdminAddSoftWareResponse{
			Code: sw_store_api.AdminAddSoftWareResponse_CODE_OK,
			SwId: swId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*sw_store_api.AdminAddSoftWareResponse), nil
}

func (apiImpl *SwStoreAdminApiImpl) UpdateSoftWare(ctx context.Context, req *sw_store_api.AdminUpdateSoftWareRequest) (*sw_store_api.AdminUpdateSoftWareResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &sw_store_api.AdminUpdateSoftWareResponse{
			Code:   sw_store_api.AdminUpdateSoftWareResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &sw_store_api.AdminUpdateSoftWareResponse{
			Code:   sw_store_api.AdminUpdateSoftWareResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SwStorePerm.UpdateSoftWare {
		return &sw_store_api.AdminUpdateSoftWareResponse{
			Code:   sw_store_api.AdminUpdateSoftWareResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	exist, err := sw_dao.CateDao.Exist(ctx, req.CateId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &sw_store_api.AdminUpdateSoftWareResponse{
			Code:   sw_store_api.AdminUpdateSoftWareResponse_CODE_NO_CATE,
			ErrMsg: "软件分类不存在",
		}, nil
	}

	softwareItem, err := sw_dao.SoftwareDao.Get(ctx, req.SwId)
	if err != nil {
		return &sw_store_api.AdminUpdateSoftWareResponse{
			Code:   sw_store_api.AdminUpdateSoftWareResponse_CODE_NO_SOFT_WARE,
			ErrMsg: "软件不存在",
		}, nil
	}

	nowTime := time.Now().UnixNano() / 1e6
	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		osList := []uint32{}
		for _, osType := range req.OsList {
			osList = append(osList, uint32(osType))
		}
		err = sw_dao.SoftwareDao.Update(sessCtx, &sw_dao.SoftWareInfoDbItem{
			SwId:        req.SwId,
			SwName:      req.SwName,
			SwDesc:      req.SwDesc,
			CateId:      req.CateId,
			Weight:      req.Weight,
			Recommend:   req.Recommend,
			OsList:      osList,
			DownloadUrl: req.DownloadUrl,
			IconFileId:  req.IconFileId,
			CreateTime:  softwareItem.CreateTime,
			UpdateTime:  nowTime,
		})
		if err != nil {
			return nil, err
		}
		{
			count, err := sw_dao.SoftwareDao.CountByCate(sessCtx, softwareItem.CateId)
			if err != nil {
				return nil, err
			}
			err = sw_dao.CateDao.UpdateSoftWareCount(sessCtx, softwareItem.CateId, count)
			if err != nil {
				return nil, err
			}
		}
		{
			count, err := sw_dao.SoftwareDao.CountByCate(sessCtx, req.CateId)
			if err != nil {
				return nil, err
			}
			err = sw_dao.CateDao.UpdateSoftWareCount(sessCtx, req.CateId, count)
			if err != nil {
				return nil, err
			}
		}
		return &sw_store_api.AdminUpdateSoftWareResponse{
			Code: sw_store_api.AdminUpdateSoftWareResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*sw_store_api.AdminUpdateSoftWareResponse), nil
}

func (apiImpl *SwStoreAdminApiImpl) RemoveSoftWare(ctx context.Context, req *sw_store_api.AdminRemoveSoftWareRequest) (*sw_store_api.AdminRemoveSoftWareResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &sw_store_api.AdminRemoveSoftWareResponse{
			Code:   sw_store_api.AdminRemoveSoftWareResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &sw_store_api.AdminRemoveSoftWareResponse{
			Code:   sw_store_api.AdminRemoveSoftWareResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SwStorePerm.RemoveSoftWare {
		return &sw_store_api.AdminRemoveSoftWareResponse{
			Code:   sw_store_api.AdminRemoveSoftWareResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	softwareItem, err := sw_dao.SoftwareDao.Get(ctx, req.SwId)
	if err != nil { //记录不存在
		return &sw_store_api.AdminRemoveSoftWareResponse{
			Code: sw_store_api.AdminRemoveSoftWareResponse_CODE_OK,
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = sw_dao.SoftwareDao.Remove(sessCtx, req.SwId)
		if err != nil {
			return nil, err
		}
		count, err := sw_dao.SoftwareDao.CountByCate(sessCtx, softwareItem.CateId)
		if err != nil {
			return nil, err
		}
		err = sw_dao.CateDao.UpdateSoftWareCount(sessCtx, softwareItem.CateId, count)
		if err != nil {
			return nil, err
		}
		return &sw_store_api.AdminRemoveSoftWareResponse{
			Code: sw_store_api.AdminRemoveSoftWareResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*sw_store_api.AdminRemoveSoftWareResponse), nil
}
